package com.magic.potato.feign.config;

import com.magic.potato.feign.annotation.FeignClient;
import com.magic.potato.feign.annotation.FeignScan;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;

/**
 * @author ycl
 * 注册扫描到的feign
 */
public class FeignScanRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        FeignClientClassPathScanner feignClientRegistrar = new FeignClientClassPathScanner(registry);
        AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(FeignScan.class.getName()));

        if (annotationAttributes != null && !annotationAttributes.isEmpty()) {
            feignClientRegistrar.scan(annotationAttributes.getStringArray("value"));
        }
    }

    static class FeignClientClassPathScanner extends ClassPathBeanDefinitionScanner {

        public FeignClientClassPathScanner(BeanDefinitionRegistry registry) {
            super(registry, false);
            // 注册过滤器
            addIncludeFilter(new AnnotationTypeFilter(FeignClient.class));
        }

        @Override
        protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
            AnnotationMetadata metadata = beanDefinition.getMetadata();
            return metadata.isIndependent() && metadata.isInterface();
        }
    }
}
